package com.lkl.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.lkl.dao.AddressDao;
import com.lkl.entity.Address;
import com.lkl.entity.AddressVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    public static String filePath = System.getProperty("user.dir") + "/doc";
    static  String jsonPath = filePath + "/data.json";
    static volatile String sqlPath = filePath + "/江苏省.sql";
    //数据条数统计
    static Long count = 0L;
    //时间统计
    static volatile Long startTime = System.currentTimeMillis();
    /**
     * 写入Json文档数据
     * @param addressList
     */
    public static void write2Data(List<Address> addressList) {
        logger.info("开始存入数据，数据条数：{}",addressList.size());
//        StringBuffer sb = new StringBuffer();
//        sb.append("insert into `test`(`code`,`name`,`parent_code`) values ");
//        addressList.forEach(address -> sb.append(address.toString()));
        AddressDao addressDao = new AddressDao();
        String sql = "insert into `test`(`code`,`name`,`parent_code`) values (?,?,?) ";
        addressDao.insertBatch(sql, addressList.toArray());
        //记录写入时间
        startTime = System.currentTimeMillis();
        logger.info("存入数据结束！");
    }

    /**
     * 将数据存入文件
     * @param addressList
     */
    public static void write2File(List<Address> addressList) {
        List<String> collect1 = addressList.stream().map(address ->
                "('" + address.getCode() + "', '" + address.getName() + "', '" + address.getParentCode() + "'),").collect(Collectors.toList());
        count += collect1.size();
        //存储的数据超过60条，加入insert语句，防止一条sql语句太长
        if (count > 60L) {
            String sql = "insert into `address`(`code`,`name`,`parent_code`) values ";
            collect1.add(sql);
            count = 0L;
        }
        FileUtil.writeLines(collect1,sqlPath, CharsetUtil.CHARSET_UTF_8,true);
        //记录写入时间
        startTime = System.currentTimeMillis();
        //记录数据总数
        JobProcessor.dataTotal += addressList.size();
    }

    /**
     * 读取JSON文档数据
     * @return
     */
    public static <T> List<T> readJson(Class<T> clazz) {
        List<String> strings = FileUtil.readLines(filePath, CharsetUtil.CHARSET_UTF_8);
         return strings.stream().map(address -> JSONObject.parseObject(address, clazz)).collect(Collectors.toList());
    }
    public static String getJson(List<Address> addresses) {
        List<AddressVO> addressVOS = new ArrayList<>();
        addresses.forEach( address -> {
            //查看是否已经有该数据了
            List<AddressVO> collect1 = addressVOS.stream().filter(
                    addressVO -> addressVO.getName().equals(address.getName())).collect(Collectors.toList());
            //大于0，有数据了。获取该数据
            AddressVO addressVO;
            if (collect1.size() > 0) {
                 addressVO = collect1.get(0);
//                System.out.println("已有数据：" + addressVO.getName());
            } else {
                //否则创建对象
                addressVO  = new AddressVO();
                addressVO.setCode(address.getName());
                addressVO.setName(address.getName());
            }
          //设置子节点
            List<Address> collect = addresses.stream().filter(
                            address1 -> address1.getParentCode().equals(address.getName()))
                    .collect(Collectors.toList());

            if (collect.size() > 0) {
                List<AddressVO> addressVOS1 = new ArrayList<>();
                collect.forEach(address1 -> {
                    AddressVO addressVO1 = new AddressVO();
                    addressVO1.setCode(address1.getName());
                    addressVO1.setName(address1.getName());
                    addressVOS1.add(addressVO1);
                });
                addressVO.setChildren(addressVOS1);
            }
            //存入判断
            String value = address.getName();
            int num = 10;
            if (value.substring(value.length() - num).equals(StringUtils.rightPad("", num, '0'))) {
                addressVOS.add(addressVO);
            }
        });
        System.out.println("结束处理数据");
        return JSONObject.toJSONString(addressVOS);
    }
}
